package httputil

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/xuri/excelize/v2"
	"io"
	"net/http"
	"os"
)

func ResponseBytes(w http.ResponseWriter, bytes []byte, fileName string) {
	if len(bytes) <= 0 {
		return
	}
	setWriteFileHeader(&w, fileName, int64(len(bytes)))
	// 将文件内容写入响应体
	_, err := w.Write(bytes)
	handleErr(w, err)
}

func setWriteFileHeader(wp *http.ResponseWriter, fileName string, size int64) {
	// 获取文件信息
	// 设置响应头
	w := *wp
	w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Length", fmt.Sprintf("%d", size))
}

func ResponseExcel(w http.ResponseWriter, f *excelize.File) {
	// 将Excel文件写入HTTP响应
	w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	w.Header().Set("Content-Disposition", "attachment; filename=example.xlsx")
	err := f.Write(w)
	handleErr(w, err)
}

func handleErr(w http.ResponseWriter, err error) {
	if err != nil {
		http.Error(w, "Failed to get file info", http.StatusInternalServerError)
		return
	}
}

func ResponseTextFile(w http.ResponseWriter, file *os.File) {
	// 获取文件信息
	fileInfo, err := file.Stat()
	if err != nil {
		handleErr(w, err)
		return
	}
	setWriteFileHeader(&w, fileInfo.Name(), fileInfo.Size())
	// 将文件内容写入响应体
	_, err = io.Copy(w, file)
	handleErr(w, err)
}

func GoPostJson(data interface{}, url string) (*http.Response, error) {
	// 创建HTTP客户端
	client := &http.Client{}
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	// 创建HTTP请求
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	req.Header.Set(ContentType, ApplicationJson)

	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if err != nil {
			return
		}
	}(resp.Body)
	return resp, nil
}
func GoGetByUrl(url string) (*http.Response, error) {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if err != nil {
			return
		}
	}(resp.Body)
	return resp, nil
}
func GoGetRequestByUrl(url string) (*http.Response, error) {
	// 创建HTTP客户端
	req, err := http.NewRequest(http.MethodGet, url, nil)
	// 创建HTTP请求
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	client := &http.Client{}
	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if err != nil {
			return
		}
	}(resp.Body)
	return resp, nil
}
